package com.hzw.saas.web.shell.controller;

import java.io.IOException;
import java.security.Principal;

import com.hzw.saas.common.util.MapperUtil;
import com.hzw.saas.web.shell.controller.param.HpcAccountParam;
import com.hzw.saas.web.shell.service.IWebShellService;
import com.hzw.saas.web.shell.service.query.HpcAccountQuery;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RestController;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 *
 * </p>
 *
 * @author sonam
 * @since 2021/5/27 18:22
 */
@Slf4j
@RestController
@RequiredArgsConstructor
public class SshController {

    private final IWebShellService webShellService;

    /**
     * 连接SSH
     */
    @MessageMapping(value = "/ssh/connect")
    public void connectionSsh(Principal principal, @Validated HpcAccountParam hpcAccountParam, StompHeaderAccessor stompHeaderAccessor) {
        HpcAccountQuery hpcAccountQuery = MapperUtil.nf().map(hpcAccountParam, HpcAccountQuery.class);
        hpcAccountQuery.setDestination("/webshell/console/" + hpcAccountParam.getUuid());
        hpcAccountQuery.setUserName(principal.getName());
        hpcAccountQuery.setSessionId(stompHeaderAccessor.getSessionId());

        // 异步执行
        webShellService.connection(hpcAccountQuery);
    }

    /**
     * 向SSH发送消息
     *
     * @param stompHeaderAccessor
     * @param command
     */
    @MessageMapping(value = "/ssh/console")
    public void sendCommand(StompHeaderAccessor stompHeaderAccessor, String command) throws IOException {
        webShellService.transToSSH(stompHeaderAccessor.getSessionId(), command);
    }

}
